package com.demo.core;

import com.demo.config.SpringContextUtil;
import com.demo.po.ApplicationPo;
import com.demo.po.ServerPo;
import com.demo.service.IServerService;
import com.demo.utils.ShellUtils;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class ActionContext {

    private static Map<String, Session> connections = new ConcurrentHashMap<>();

    private static Session build(ServerPo server) {
        Session session = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(server.getSshname(), server.getHost(), server.getSshport());
            session.setPassword(server.getSshpwd());
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setTimeout(ShellUtils.DEFAULT_TIMEOUT);
            session.connect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return session;
    }

    public static Session getSession(ServerPo server) {
        if (connections.containsKey(String.valueOf(server.getServerid()))) {
            Session session = connections.get(String.valueOf(server.getServerid()));
            if (session != null && session.isConnected())
                return session;
        }
        Session session = build(server);
        connections.put(String.valueOf(server.getServerid()), session);
        return session;
    }

    public static Session getSession(Integer serverid) {
        if (connections.containsKey(String.valueOf(serverid))) {
            Session session = connections.get(String.valueOf(serverid));
            if (session != null && session.isConnected())
                return session;
        }
        IServerService serverService = SpringContextUtil.getBean("serverService");
        ServerPo server = serverService.getServer(serverid);
        Session session = build(server);
        connections.put(String.valueOf(serverid), session);
        return session;
    }

    public static String testApp(ApplicationPo application) {
        String remark = "";

        Session session = ActionContext.getSession(application.getServerid());
        if (session == null) {
            remark = "服务器连接失败！";
            application.setAppstatus(3);
            application.setErrormsg(remark);
            return remark;
        }
        if (!ShellUtils.exists(session, application.getDeveloppath())) {
            remark = "部署路径不存在！";
            application.setAppstatus(3);
            application.setErrormsg(remark);
            return remark;
        }
        if (!ShellUtils.exists(session, SysConfig.concat(application.getDeveloppath(), "a.sh"))) {
            if (StringUtils.isBlank(application.getAppshell())) {
                remark = "应用脚本未配置！";
                application.setAppstatus(3);
                application.setErrormsg(remark);
                return remark;
            }
            boolean result = ShellUtils.execFtp(session, application.getAppshell(), SysConfig.concat(application.getDeveloppath(), "a.sh"));
            if (!result) {
                remark = "应用脚本部署失败！";
                application.setAppstatus(3);
                application.setErrormsg(remark);
                return remark;
            }
            List<String> list = ShellUtils.execCmd(session, "cd " + application.getDeveloppath() + " && dos2unix a.sh");
            if (list == null) {
                remark = "应用脚本格式转换失败！";
                application.setAppstatus(3);
                application.setErrormsg(remark);
                return remark;
            }
            for (String line : list) {
                if (line.contains("command not found")) {
                    remark = "dos2unix工具未安装，请手工安装：yum install dos2unix";
                    application.setAppstatus(3);
                    application.setErrormsg(remark);
                    return remark;
                }
            }
        }
        List<String> list = ShellUtils.execCmd(session, "cd " + application.getDeveloppath() + " && sh a.sh status");
        if (list == null) {
            remark = "执行应用脚本失败！";
            application.setAppstatus(3);
            application.setErrormsg(remark);
            return remark;
        }
        for (String line : list) {
            if (line.contains("is running")) {
                remark = "应用正在运行中......";
                application.setAppstatus(0);
                application.setErrormsg(remark);
            } else if (line.contains("is stopped")) {
                remark = "应用已经停止！";
                application.setAppstatus(1);
                application.setErrormsg(remark);
            }
        }
        return remark;
    }
}
